#include "rtp.h"

#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>

void rtpWriteData(struct RtpPacket* rtpPacket, uint8_t* frame,
                  uint32_t dataSize) {
  rtpPacket->rtpHeader.seq = htons(rtpPacket->rtpHeader.seq);
  rtpPacket->rtpHeader.timestamp = htonl(rtpPacket->rtpHeader.timestamp);
  rtpPacket->rtpHeader.ssrc = htonl(rtpPacket->rtpHeader.ssrc);
  int size = dataSize + RTP_HEADER_SIZE;
  uint8_t* ptr = rtpPacket->payload + rtpPacket->offset;
  ptr[0] = 0x24;
  ptr[1] = 0;
  ptr[2] = (size >> 8) & 0xff;
  ptr[3] = size & 0xff;
  memcpy(ptr + 4, &rtpPacket->rtpHeader, RTP_HEADER_SIZE);
  memcpy(ptr + 16, frame, dataSize);
  rtpPacket->offset += (size + 4);
  rtpPacket->rtpHeader.seq = ntohs(rtpPacket->rtpHeader.seq);
  rtpPacket->rtpHeader.timestamp = ntohl(rtpPacket->rtpHeader.timestamp);
  rtpPacket->rtpHeader.ssrc = ntohl(rtpPacket->rtpHeader.ssrc);
  rtpPacket->rtpHeader.seq++;
}

void rtpHeaderInit(struct RtpPacket* rtpPacket, uint8_t csrcLen,
                   uint8_t extension, uint8_t padding, uint8_t version,
                   uint8_t payloadType, uint8_t marker, uint16_t seq,
                   uint32_t timestamp, uint32_t ssrc) {
  rtpPacket->rtpHeader.csrcLen = csrcLen;
  rtpPacket->rtpHeader.extension = extension;
  rtpPacket->rtpHeader.padding = padding;
  rtpPacket->rtpHeader.version = version;
  rtpPacket->rtpHeader.payloadType = payloadType;
  rtpPacket->rtpHeader.marker = marker;
  rtpPacket->rtpHeader.seq = seq;
  rtpPacket->rtpHeader.timestamp = timestamp;
  rtpPacket->rtpHeader.ssrc = ssrc;
  rtpPacket->payload = malloc(500000);
  rtpPacket->offset = 0;
}

int rtpSendPacket(int socket, const char* ip, int16_t port,
                  struct RtpPacket* rtpPacket) {
  // struct sockaddr_in addr;
  // addr.sin_family = AF_INET;
  // addr.sin_port = htons(port);
  // addr.sin_addr.s_addr = inet_addr(ip);
  int ret = send(socket, rtpPacket->payload, rtpPacket->offset, MSG_NOSIGNAL);
  rtpPacket->offset = 0;
  // printf("rtpSendPacket %d\n", ret);
  return ret;
}
